package com.uenpay.im.ui.old.activity.dynamic;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.RecyclerListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.CameraActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.panel.FacePanelByEmojiManager;
import com.uenpay.im.panel.PanelManagerInterface;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.im.weight.listview.RefreshListView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * @author SL
 * @created 2015-12-16 11:57:57
 * @copyRight http://www.qiyunxin.com
 * @function I published dynamics or a friend dynamics published list
 */
public class PersonalDynamicActivity extends BaseActivity implements
		OnClickListener, RefreshListView.IRefreshListViewListener {
	private DynamicHandle mDynamicHandle = new DynamicHandle();
	private RefreshListView mListView;
	private TextView nick_tv;
	private RoundImageView photo_iv;
	private MaskImageView bg_dynamic_iv;
	private ArrayList<DynamicEntity> dynamics = new ArrayList<DynamicEntity>();
	private static final int SEND_DYNAMIC = 2;
	private View loading;
	private int page = 1;
	private int replyDynamicId;
	private EditText editText;
	private View dynamic_pop_reply;
	protected FileUtils fileUtils = new FileUtils(IMApplication.appName);
	private static final int PAIS = 1;
	private static final int PIC = 0;
	private DynamicAdapter adapter;
	private LinearLayout linearLayout1;
	private String cust_id;
	private boolean is_restore;
	private int replySourceCustId;
	private String picPath;
	private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();
	private ArrayList<ImageSize> size = new ArrayList<ImageSize>();
	private String personalName = "";
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 3:
				alterAlbumBg();
				break;
			case 5:
				if (page == 1) {
					if (adapter != null) {
						adapter.setData(dynamics);
					} else {
						initData();
					}
					mListView.setSelection(0);
					page++;
				} else {
					adapter.addData(dynamics);
					page++;
				}
				break;
			case 6:
				if (loading != null) {
					loading.setVisibility(View.GONE);
				}
				break;
			default:
				break;
			}
		};
	};

	private FacePanelByEmojiManager mFacePanelByEmojiManager;
	private ResizeLayout mResizeLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen=true;
		super.onCreate(savedInstanceState);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_friend_dynamic;
	}

	@Override
	public void initView(View view) {
		loading = findViewById(R.id.dynamic_loading);
		loading.setVisibility(View.VISIBLE);
		cust_id = getIntent().getStringExtra("cust_id");
		personalName = getIntent().getStringExtra("cust_name");
		initView();
		initFacePanelView();
		initListener();
		initData();
		getDynamic();
	}

	private void initFacePanelView() {
		mFacePanelByEmojiManager = new FacePanelByEmojiManager(this,
				dynamic_pop_reply, mResizeLayout);
		mFacePanelByEmojiManager.initListener();
		mFacePanelByEmojiManager.onSendTextListener(new PanelManagerInterface.ISendTextListener() {

			@Override
			public void onSendTextContent(String editContent) {
				if (!TextUtils.isEmpty(editContent.trim())) {
					if (editContent.length() <= 140) {
						Utils.hideSoftKeyboard(editText);
						dynamic_pop_reply.setVisibility(View.GONE);
						if (is_restore) {
							replyDynamic(editContent);
							is_restore = false;
							editText.setHint("");
						} else {
							replyDynamic(editContent);
						}

					} else {
						IMApplication.showToast(R.string.more_text_max);
					}
				} else {
					IMApplication.showToast(R.string.reply_empty);
				}
			}
		});
	}

	protected void initView() {
		findViewById(R.id.title_right_layout).setOnClickListener(this);

		if (TextUtils.isEmpty(personalName)) {
			((TextView) findViewById(R.id.title_textview))
					.setText(R.string.friend_circle);
		} else {
			((TextView) findViewById(R.id.title_textview))
					.setText(personalName);
		}
		((TextView) findViewById(R.id.title_right_tv))
				.setText(R.string.main_msg);
		mListView = (RefreshListView) findViewById(R.id.listview_dynamic);
		mListView.setScrollingCacheEnabled(false);
		mListView.setFastScrollEnabled(false);
		editText = (EditText) findViewById(R.id.editText);
		dynamic_pop_reply = findViewById(R.id.dynamic_pop_reply);
		mResizeLayout = (ResizeLayout) findViewById(R.id.parent);
		View view = LayoutInflater.from(this).inflate(
				R.layout.activity_friend_dynamic_head, null);
		mListView.addHeaderView(view);
		nick_tv = (TextView) view.findViewById(R.id.nick_tv);
		photo_iv = (RoundImageView) view.findViewById(R.id.dynamic_photo_btn);
		bg_dynamic_iv = (MaskImageView) view.findViewById(R.id.bg_dynamic_iv);
		linearLayout1 = (LinearLayout) view.findViewById(R.id.linearLayout1);

		if (cust_id.equals(IMApplication.getCustId())) {
			if (!TextUtils.isEmpty(IMApplication.config.getDynamicBg())) {
				linearLayout1.setVisibility(View.GONE);
				bg_dynamic_iv.SetUrl(IMApplication.config.getDynamicBg());
			}
			findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
			nick_tv.setText(IMApplication.config.getUserName());
		} else {
			findViewById(R.id.title_right_layout).setVisibility(View.GONE);
			findViewById(R.id.update_dynamic_bg_tv).setVisibility(View.GONE);
		}
		photo_iv.SetUrl(APIConfiguration.getAvatarUrlNormal(cust_id,
				PacketType.PERSONAL));
	}

	protected void initListener() {
		mListView.setPullLoadEnable(true);
		mListView.setRefreshListViewListener(this);
		findViewById(R.id.back_layout).setOnClickListener(this);
		photo_iv.setOnClickListener(this);
		bg_dynamic_iv.setOnClickListener(this);

		mListView.setRecyclerListener(new RecyclerListener() {
			@Override
			public void onMovedToScrapHeap(View view) {
				if (view.getTag() instanceof DynamicAdapterViewHolder.DynamicBaseViewHolder) {
					DynamicAdapterViewHolder.DynamicBaseViewHolder holder = (DynamicAdapterViewHolder.DynamicBaseViewHolder) view
							.getTag();
					if (holder == null) {
						return;
					}
					if (holder.position >= mListView.getFirstVisiblePosition()
							&& holder.position <= mListView
									.getLastVisiblePosition()) {
						return;
					}
					holder.mReplyLLayout.removeAllViews();
				}
			}
		});

		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mFacePanelByEmojiManager != null) {
					mFacePanelByEmojiManager.hideFacePanelView();
				}
				dynamic_pop_reply.setVisibility(View.GONE);
				return false;
			}
		});

	}

	public void initData() {
		adapter = new DynamicAdapter(editText, this, dynamics,
				new DynamicAdapter.IDynamicReplyListener() {

					@Override
					public void onDynamicReply(int dynamicId,
							int source_cust_id, int position) {
						// TODO 评论
						replyDynamicId = dynamicId;
						replySourceCustId = source_cust_id;
						if (source_cust_id > 0) {
							is_restore = true;
						}
						dynamic_pop_reply.setVisibility(View.VISIBLE);
						if (mFacePanelByEmojiManager != null) {
							mFacePanelByEmojiManager.showFacePanelView();
							Utils.showSoftKeyboard(editText);
						}
						mListView.setSelection(mListView.getHeaderViewsCount()
								+ position);

					}
				});
		mListView.setAdapter(adapter);
	}

	public void delDynamic(int dynamicPosition) {
		mDynamicHandle.deleteDynamic(
				Integer.parseInt(adapter.getItem(dynamicPosition).dynamicid),
				new DynamicHandle.IDynamicResult() {

					@Override
					public void onDynamicResult(int status, String msg) {
						if (status == HttpInvokeResultCode.RESULT_OK) {
							handler.sendEmptyMessage(1);
						}
					}
				});

	}

	private void hideSoftKeyboard() {
		if (editText != null) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	private void replyDynamic(final String content) {
		loading.setVisibility(View.VISIBLE);
		mDynamicHandle.replyDynamic(replySourceCustId, replyDynamicId, content,
				new DynamicHandle.IReplyDynamicResultListener() {

					@Override
					public void onReplyDynamicReslut(int status, String msg,
							Reply mReply) {
						if (isFinishing())
							return;
						handler.sendEmptyMessage(6);
						if (status == HttpInvokeResultCode.RESULT_OK) {
							editText.setText("");
							Utils.hideSoftKeyboard(editText);
							Reply r = new Reply();
							r.replyid = mReply.replyid;
							r.nickname = IMApplication.config.getUserName();
							r.content = mReply.content;
							r.custid = mReply.custid;
							r.pcustid = mReply.pcustid;
							r.pnickname = mReply.pnickname;
							adapter.updateReply(r, replyDynamicId);
						}
					}
				});

	}

	public void alterAlbumBg() {
		String url = APIConfiguration.getBaseUrl()
				+ "Dynamic/Dynamic/setBackground?"
				+ APIConfiguration.getCustIdAndToken();
		if (picPath.startsWith("http")) {
			picPath = HttpStreamCache.getInstance().GetFilePath(picPath);
		}
		HttpRequestAsyncTaskQueue.getInstance().AddTask(
				new HttpUploadFileAsyncTask("1", picPath, url, "uploadedFile") {

				}, new OnUploadFileListener() {

					@Override
					public void OnSuccess(String key, String response) {
						FileMessage fileMessage = new FileMessage();
						try {
							JSONObject json = new JSONObject(response);
							fileMessage.status = json.optInt("status");
							JSONObject dataJson = json.optJSONObject("data");
							if (dataJson != null) {
								JSONObject dynamicSetting = dataJson
										.optJSONObject("dynamicsetting");
								if (dynamicSetting != null) {
									fileMessage.filehash = dynamicSetting
											.optString("bgfilehash");
									fileMessage.fileid = dynamicSetting
											.optString("bgfileid");
								}

								IMApplication.config
										.setDynamicBg(APIConfiguration
												.getFileDownloadPath(
														fileMessage.fileid,
														fileMessage.filehash));
								bg_dynamic_iv.SetUrl(APIConfiguration
										.getFileDownloadPath(
												fileMessage.fileid,
												fileMessage.filehash));
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void OnFail(String key, String reason) {

					}
				});

		linearLayout1.setVisibility(View.GONE);
	}

	public void getDynamic() {
		mDynamicHandle.getDynamicPersonalList(page, cust_id,
				new DynamicHandle.IGetDynamicPersonalListResultListener() {

					@Override
					public void onGetDynamicPersonalResult(int status,
							String msg,
							ArrayList<DynamicEntity> ResultDynamics,
							String dynamicBgFileId, String dynamicBgFileHash) {
						if (isFinishing()) {
							return;
						}
						onLoad();
						handler.sendEmptyMessage(6);
						if (status == HttpInvokeResultCode.RESULT_OK) {
							if (ResultDynamics != null) {
								if (ResultDynamics.size() > 0) {
									dynamics = ResultDynamics;
									Message message = handler.obtainMessage();
									message.what = 5;
									message.obj = ResultDynamics;
									handler.sendMessage(message);
								} else if (page != 1) {
									mListView.setPullLoadEnable(false);
								}
							} else if (page != 1) {
								mListView.setPullLoadEnable(false);
							}

							if (!cust_id.equals(IMApplication.getCustId())) {
								bg_dynamic_iv.SetUrl(APIConfiguration
										.getFileDownloadPath(dynamicBgFileId,
												dynamicBgFileHash));
							}
						} else {
							mListView.setPullLoadEnable(false);
						}

					}
				});
	}

	@Override
	public void onClick(View v) {
		int i = v.getId();
		if (i == R.id.back_layout) {
			hideSoftKeyboard();
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					finish();
				}
			}, 300);


		} else if (i == R.id.title_right_layout) {
			ActivityHandle.startActivity(PersonalDynamicActivity.this,
					DynamicHistoryActivity.class, null, -1);

		} else if (i == R.id.send_btn) {
			String reply = editText.getText().toString();
			if (!TextUtils.isEmpty(reply.trim())) {
				if (reply.length() <= 140) {
					Utils.hideSoftKeyboard(editText);
					dynamic_pop_reply.setVisibility(View.GONE);
					if (is_restore) {
						replyDynamic(reply);
						is_restore = false;
						editText.setHint("");
					} else {
						replyDynamic(reply);
					}

				} else {
					IMApplication.showToast(R.string.more_text_max);
				}
			} else {
				IMApplication.showToast(R.string.reply_empty);
			}

		} else if (i == R.id.bg_dynamic_iv) {
			if (cust_id.equals(IMApplication.getCustId())) {
				showBgDialog();
			}

		} else {
		}
	}

	public void showBgDialog() {

		BottomDialog.showBottomDialog(PersonalDynamicActivity.this,
				getResources().getString(R.string.take_photo), getResources()
						.getString(R.string.take_image), getResources()
						.getString(R.string.cancel), -1,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						size.clear();
						size.add(new ImageSize(720, 720, ""));
						Bundle bundle = new Bundle();
						bundle.putSerializable("size", size);
						ActivityHandle.startActivity(PersonalDynamicActivity.this,
								CameraActivity.class, bundle, PAIS);
					}
				}, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						Bundle bundle = new Bundle();
						bundle.putInt("max_select_count", 1);
						ActivityHandle.startActivity(PersonalDynamicActivity.this,
								PhotoActivity.class, bundle, PIC);
					}
				});

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			File compressFile = null;
			Bitmap compressBitmap = null;
			switch (requestCode) {
			case SEND_DYNAMIC:
				page = 1;
				getDynamic();
				break;
			case PAIS:
				try {
					picPath = data.getStringExtra("big_pic_filename");
					// bytes = fileUtils.getBytesFromFile(new File(picPath));
					handler.sendEmptyMessage(3);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case PIC:
				try {

					select_gl_arr.clear();
					select_gl_arr = (ArrayList<PhotoItem>) data
							.getSerializableExtra("gl_arr");

					if (select_gl_arr.size() > 0) {
						for (int i = 0; i < select_gl_arr.size(); i++) {
							String path = select_gl_arr.get(i).getPath();
							compressFile = new File(fileUtils.getAlbumDir(),
									Utils.md5(path) + ".jpg");
							compressBitmap = ImageUtil.CompressImage(path, 90,
									720, 720);
							FileOutputStream fos;
							fos = new FileOutputStream(compressFile);
							compressBitmap.compress(Bitmap.CompressFormat.JPEG,
									80, fos);
							picPath = compressFile.getAbsolutePath();
							// firstPic = compressFile.getAbsolutePath();
							// bytes = fileUtils.getBytesFromFile(compressFile);
							handler.sendEmptyMessage(3);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			default:
				break;
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		if (adapter != null) {
			adapter.RecycleMaskImageView(true);
		}
		super.onDestroy();
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		page = 1;
		getDynamic();
	}

	@Override
	public void onLoadMore() {
		getDynamic();
	}

}
